package com.al.study.record.sort;

/**
 * Created by yuxi on 2017/9/3.
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {-2, 1, 33, 4, 5, 0, 0, -1, 45, 908, 3};
        int low = 0;
        int high = arr.length - 1;
        quickSort(arr, low, high);
        for (int i : arr) {
            System.out.print(i + "  ");
        }
    }

    private static void quickSort(int[] arr, int low, int high) {
        if (low >= high) return;
        int p1 = getPartion(arr, low, high);
        int p = getPartionOne(arr, low, high);
        System.out.println(p1 == p);
        quickSort(arr, low, p - 1);
        quickSort(arr, p + 1, high);
    }

    private static int getPartionOne(int[] arr, int left, int right) {
        int tmp = arr[left];
        int i = left;
        int j = right + 1;
        while (true) {
            while (arr[++i] < tmp) {

            }
            while (arr[--j] > tmp) {

            }
            if (i >= j) {
                break;
            }
            exchage(arr, i, j);
        }
        exchage(arr, left, j);
        return left;
    }

    private static void exchage(int[] arr, int i, int j) {
        int aux = arr[i];
        arr[i] = arr[j];
        arr[j] = aux;
    }

    private static int getPartion(int[] arr, int left, int right) {
        int tmp = arr[left];
        while (left < right) {
            while (left < right && arr[right] > tmp)
                right--;
            arr[left] = arr[right];

            while (left < right && arr[left] <= tmp)
                left++;
            arr[right] = arr[left];
        }
        arr[left] = tmp;
        return left;
    }
}
